package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import client.ClientConsole;

import logic.BookItem;
import logic.Librarian;
import logic.Message;
import logic.PdfFile;
import logic.Reader;
import logic.Title;

/**
 * shows search results for search query and option given by the user
 * enables order books if out of stock and view table of contents
 */
public class SearchForm extends JPanel implements ActionListener{
	/** query string  for search*/
	private String query;
	/** search option*/
	private String option;
	/** holds search results */
	private Object[][] o;
	/** used to display feedback from server*/
	private JLabel error,orderConfirmation;
	/** reference for a title*/
	Title t;
	/** a request for order book*/
	Object[] orderRequset=new Object[2];
	/** message form server about search results */
	Message msg;
	/** reference for a title*/
	Title title;
	JButton back,order,pdfFile;
	/**  GUI Panel used for Design*/
	JPanel mainPanel,bottomPanel,errorPanel,scrollPanel;
	/** saves the properties of the GridBagLayout for*/
	GridBagConstraints gbc;
		
		/**
		 * @param query the Search string
		 * @param option the option of search
		 */
		public SearchForm(String query,String option)
		{
			super();
			
			int i=0;
			int index=0;
			this.query=query;
			this.option=option;
			scrollPanel=new JPanel();
			scrollPanel.setLayout(new BorderLayout());
			setLayout(new BorderLayout());
			orderConfirmation=new JLabel();
			getResult();
			if (msg.getCommand().equals("Book found"))
			{
				mainPanel=new JPanel();
				mainPanel.setLayout(new GridBagLayout());
				for (index=0; index<o.length; index++)
				{
					
					JLabel bookNameLabel=new JLabel("Name: ");
					gbc = new GridBagConstraints();
					gbc.gridx=1;
					gbc.gridy=i;
					gbc.insets= new Insets(4,4,4,4);
					mainPanel.add(bookNameLabel,gbc);
					title=(Title) o[index][0];
					JLabel bookName=new JLabel(title.getName());
					gbc = new GridBagConstraints();
					gbc.gridx=2;
					gbc.gridy=i;
					gbc.insets= new Insets(4,4,4,4);
					mainPanel.add(bookName,gbc);
					if (((String) o[index][1]).equals("0"))
					{
						JLabel img=new JLabel();
						img.setIcon(new ImageIcon("C://images//bookok.png"));
						gbc = new GridBagConstraints();
						gbc.gridx=0;
						gbc.gridy=i++;
						gbc.gridheight=3;
						gbc.insets= new Insets(4,4,4,4);
						mainPanel.add(img,gbc);
						JLabel locationLabel=new JLabel("Location: ");
						gbc = new GridBagConstraints();
						gbc.gridx=1;
						gbc.gridy=i;
						gbc.insets= new Insets(4,4,4,4);
						mainPanel.add(locationLabel,gbc);
						JLabel location=new JLabel(title.getShelfLocation());
						gbc = new GridBagConstraints();
						gbc.gridx=2;
						gbc.gridy=i++;
						gbc.insets= new Insets(4,4,4,4);
						mainPanel.add(location,gbc);
						JLabel notification=new JLabel("Available copies exist!!");
						notification.setForeground(Color.green);
						gbc = new GridBagConstraints();
						gbc.gridx=1;
						gbc.gridy=i++;
						gbc.gridwidth=2;
						gbc.insets= new Insets(4,4,4,4);
						mainPanel.add(notification,gbc);
						pdfFile=new JButton("Open Lable Of Contex");
						pdfFile.setName(title.tableOfContents.getFileName());
						pdfFile.addActionListener(this);
						System.out.println("name"+pdfFile.getName());
						pdfFile.addActionListener(this);
						gbc = new GridBagConstraints();
						gbc.gridx=1;
						gbc.gridy=i++;
						gbc.gridwidth=2;
						gbc.insets= new Insets(4,4,4,4);
						mainPanel.add(pdfFile,gbc);
						JLabel space=new JLabel(" ");
						gbc = new GridBagConstraints();
						gbc.gridx=1;
						gbc.gridy=i++;
						gbc.gridwidth=2;
						mainPanel.add(space,gbc);
					}
					else
					{
						String pattern="dd/MM/yyyy";
						SimpleDateFormat dateFormat=new SimpleDateFormat(pattern);
						String pattern2="yyyy-MM-dd";
						Date d=null;
						SimpleDateFormat dateFormat2=new SimpleDateFormat(pattern2);
						JLabel img=new JLabel();
						img.setIcon(new ImageIcon("C://images//booknotok.png"));
						gbc = new GridBagConstraints();
						gbc.gridx=0;
						gbc.gridy=i++;
						gbc.gridheight=4;
						gbc.insets= new Insets(4,4,4,4);
						mainPanel.add(img,gbc);
						JLabel returnDateLabel=new JLabel("Nearest return date: ");
						gbc = new GridBagConstraints();
						gbc.gridx=1;
						gbc.gridy=i;
						gbc.insets= new Insets(4,4,4,4);
						mainPanel.add(returnDateLabel,gbc);
						
						try {
							d=dateFormat2.parse((String) o[index][1]);
						} catch (ParseException e) {
							e.printStackTrace();
							System.out.print("Date Parsinf error");
						}
						JLabel returnDate=new JLabel(dateFormat.format(d));
						gbc = new GridBagConstraints();
						gbc.gridx=2;
						gbc.gridy=i++;
						gbc.insets= new Insets(4,4,4,4);
						mainPanel.add(returnDate,gbc);
						JLabel notification=new JLabel("No available copy exists!!");
						notification.setForeground(Color.red);
						gbc = new GridBagConstraints();
						gbc.gridx=1;
						gbc.gridy=i++;
						gbc.gridwidth=2;
						gbc.insets= new Insets(4,4,4,4);
						mainPanel.add(notification,gbc);
						pdfFile=new JButton("Open Lable Of Contex");
						pdfFile.setName(title.tableOfContents.getFileName());
						System.out.println("name"+pdfFile.getName());
						pdfFile.addActionListener(this);
						gbc = new GridBagConstraints();
						gbc.gridx=1;
						gbc.gridy=i++;
						gbc.gridwidth=2;
						gbc.insets= new Insets(4,4,4,4);
						mainPanel.add(pdfFile,gbc);
						if (ClientConsole.reader!=null)
						{
							order=new JButton("order");
							order.setName(String.valueOf(index));
							gbc = new GridBagConstraints();
							gbc.gridx=1;
							gbc.gridy=i++;
							gbc.gridwidth=2;
							gbc.insets= new Insets(4,4,4,4);
							order.addActionListener(this);
							mainPanel.add(order,gbc);
						}
						JLabel space=new JLabel(" ");
						gbc = new GridBagConstraints();
						gbc.gridx=1;
						gbc.gridy=i++;
						gbc.gridwidth=2;
						mainPanel.add(space,gbc);
						
					}
				}
				scrollPanel.add(mainPanel,BorderLayout.NORTH);
				
				
			}
			else
			{
				errorPanel=new JPanel();
				error=new JLabel(msg.getCommand());
				errorPanel.add(error);
				scrollPanel.add(errorPanel,BorderLayout.CENTER);
			}
			bottomPanel=new JPanel();
			back=new JButton("Back");
			back.addActionListener(this);
			bottomPanel.add(back);			
			bottomPanel.add(orderConfirmation);
			orderConfirmation.setVisible(false);
			scrollPanel.add(bottomPanel,BorderLayout.SOUTH);
			JScrollPane thePane = new JScrollPane(scrollPanel);
			add(thePane,BorderLayout.CENTER);
		}
		
		private void getResult()
		{

			
			msg=new Message ("Search Book",null,option,query);
			ClientConsole.HandleMessageFromGui(msg);
			msg=(Message)ClientConsole.client.getMessage();
			
			if(msg.getCommand().equals("Book not found,try again")) 
				return;
			
			o=(Object[][]) msg.getObjects();
			orderConfirmation.setVisible(false);
			
				  int len=o.length;
				  Title[] t=new Title[len];
				
				//  System.out.println(t[0].getTableOfContents().getFileName());
			for(int i=0;i<len;i++)
			{
				t[i]=(Title)o[i][0];
				PdfFile pdf =new PdfFile(t[i].getTableOfContents().getFileName(),t[i].getTableOfContents().getFileSize(),t[i].getTableOfContents().getFIS());
				
				  File file=new File("c://clientpdf//"+pdf.getFileName());
				  if (file.exists())
					    file.delete();
					    
			  FileOutputStream d = null;
			  
			  byte mybytearray[] = pdf.getFIS();
				
				// set output stream to write file in file system
			    BufferedOutputStream bos;
				try {
					bos = new BufferedOutputStream(new FileOutputStream(file));
				    bos.write(mybytearray, 0 , mybytearray.length); //write out file
				    bos.flush(); //close buffer
				    bos.close();
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			
			
		}

		@Override
		public void actionPerformed(ActionEvent ae) {
			if (ae.getSource()==back)
			{
				this.setVisible(false);
				if (ClientConsole.reader instanceof LibraryManager)
					ClientConsole.aFrame.setContentPane(new LibraryManagerWindow());
				else if (ClientConsole.reader instanceof Librarian)
					ClientConsole.aFrame.setContentPane(new LibrarianWindow());
				else if (ClientConsole.reader instanceof Reader)
					ClientConsole.aFrame.setContentPane(new ReaderWindow());
				else if (ClientConsole.reader ==null)
					ClientConsole.aFrame.setContentPane(new GuestWindow());
			}
			
			
			else 
			{
				System.out.println("pdf:"+((JButton)ae.getSource()).getName());
				if (((JButton)ae.getSource()).getName().contains("pdf")	){
					
					
					try {
						Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + "c://clientpdf//"+((JButton)ae.getSource()).getName());
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				else{
				int index=Integer.parseInt(((JButton)ae.getSource()).getName());
				t=(Title) o[index][0];
				BookItem bookitem=new BookItem(t.getCatalogNumber());
				Reader reader=ClientConsole.reader;
				orderRequset[0]=bookitem;
				orderRequset[1]=reader;
				msg=new Message ("Order Book",orderRequset);
				ClientConsole.HandleMessageFromGui(msg);
				msg=(Message)ClientConsole.client.getMessage();
				if (msg.getCommand().equals("Order Added"))
				{
					orderConfirmation.setVisible(true);
					orderConfirmation.setText(msg.getCommand());
				}
				else
				{
					orderConfirmation.setVisible(true);
					orderConfirmation.setText(msg.getCommand());
				}
					
				System.out.print("index:"+((JButton)ae.getSource()).getName());
			}
		}
	}
		
}


